//package cc.tuhaolicai.mt.user.mobile.service;
//
//import cc.tuhaolicai.mt.model.BoolParams;
//import cc.tuhaolicai.mt.model.DO.capital.AmountFlow;
//import cc.tuhaolicai.mt.model.DO.capital.PurchaseLoanRecord;
//import cc.tuhaolicai.mt.model.DO.loan.loan.Loan;
//import cc.tuhaolicai.mt.model.DO.loan.loan.LoanInfo;
//import cc.tuhaolicai.mt.model.DO.loan.loan.Repay;
//import cc.tuhaolicai.mt.model.DO.loan.loan.RepayUser;
//import cc.tuhaolicai.mt.model.DO.pays.payPlatform.result.TransferReturn;
//import cc.tuhaolicai.mt.model.DO.pays.payPlatform.result.TransferReturnJsonList;
//import cc.tuhaolicai.mt.model.DO.user.AccountModel;
//import cc.tuhaolicai.mt.model.DO.user.UserModel;
//import cc.tuhaolicai.mt.model.JsonResult;
//import cc.tuhaolicai.mt.model.VO.loan.LoanDetailVO;
//import cc.tuhaolicai.mt.model.VO.user.UserAccountVo;
//import cc.tuhaolicai.mt.model.workflow.Param;
//import cc.tuhaolicai.mt.predefined.constant.GenConstant;
//import cc.tuhaolicai.mt.predefined.constant.SysConfigConstant;
//import cc.tuhaolicai.mt.predefined.constant.loan.LoanStatus;
//import cc.tuhaolicai.mt.predefined.constant.loan.RepayStatus;
//import cc.tuhaolicai.mt.predefined.database.PageInfo;
//import cc.tuhaolicai.mt.predefined.database.Paging;
//import cc.tuhaolicai.mt.predefined.generate.ToolGen;
//import cc.tuhaolicai.mt.predefined.tool.ToolDate;
//import cc.tuhaolicai.mt.predefined.tool.ToolLock;
//import cc.tuhaolicai.mt.predefined.tool.ToolOrderCode;
//import cc.tuhaolicai.mt.service.common.AmountFlowBuild;
//import cc.tuhaolicai.mt.service.common.PayerMap;
//import cc.tuhaolicai.mt.service.common.TypeConst;
//import cc.tuhaolicai.mt.service.dao.loan.LoanDao;
//import cc.tuhaolicai.mt.service.dao.loan.RepayDao;
//import cc.tuhaolicai.mt.service.dao.loan.RepayUserDao;
//import cc.tuhaolicai.mt.service.exception.dao.DaoException;
//import cc.tuhaolicai.mt.service.exception.dao.DbType;
//import cc.tuhaolicai.mt.service.exception.service.InputException;
//import cc.tuhaolicai.mt.service.exception.service.PayerErrorException;
//import cc.tuhaolicai.mt.service.exception.service.loan.RepayException;
//import cc.tuhaolicai.mt.service.service.impl.RemoteService;
//import cc.tuhaolicai.mt.service.service.impl.pays.ThirdPartyServiceImpl;
//import cc.tuhaolicai.mt.service.service.impl.user.CapitalServiceImpl;
//import cc.tuhaolicai.mt.service.service.impl.user.UserServiceImpl;
//import cc.tuhaolicai.mt.service.service.union.loan.RepayService;
//import cc.tuhaolicai.mt.service.service.union.pays.ThirdPartyService;
//import cc.tuhaolicai.mt.service.service.union.user.CapitalService;
//import cc.tuhaolicai.mt.service.service.union.user.UserService;
//import cc.tuhaolicai.mt.service.wrapper.loan.LoanWrapper;
//import cc.tuhaolicai.mt.service.wrapper.loan.WorkflowWrapper;
//import cc.tuhaolicai.mt.valid.LoanMoney;
//import com.google.common.collect.Lists;
//import com.google.common.collect.Maps;
//import com.jfinal.aop.Duang;
//import org.asyou.redis.lock.ILock;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import pro.tools.data.decimal.Decimal;
//import pro.tools.data.text.ToolJson;
//import pro.tools.data.text.ToolRandoms;
//import pro.tools.data.text.ToolStr;
//import pro.tools.format.ToolFormat;
//import pro.tools.http.jdk.ToolHttp;
//import pro.tools.http.pojo.HttpReceive;
//import pro.tools.time.DatePlus;
//
//import java.io.UnsupportedEncodingException;
//import java.net.URLDecoder;
//import java.util.Date;
//import java.util.List;
//import java.util.Map;
//
///**
// * 还款方面的业务逻辑
// *
// * @author SeanDragon
// * <p>
// * Create By 2017-07-14 17:25
// */
//public class RepayServiceImpl extends RemoteService implements RepayService {
//
//    @Override
//    protected String getMapping() {
//        return "repayLoanService";
//    }
//
//    private static final Logger log = LoggerFactory.getLogger(cc.tuhaolicai.mt.service.service.impl.loan.RepayServiceImpl.class);
//
//    private static RepayDao repayDao = new RepayDao();
//    private static RepayUserDao repayUserDao = new RepayUserDao();
//    private static LoanWrapper loanWrapper = new LoanWrapper();
//    private static CapitalService capitalService = new CapitalServiceImpl();
//
//    private static UserService userService = new UserServiceImpl();
//
//    private static ThirdPartyService thirdPartyService = new ThirdPartyServiceImpl();
//
//    //    private static PurchaseLoanRecordService purchaseLoanRecordService = new PurchaseLoanRecordServiceImpl();
//    @Override
//    public Boolean putRepay(Loan loan, LoanInfo loanInfo) throws InputException {
//
//        if (loan.getLoanId() == null
//                || ToolStr.isBlank(loan.getLoanNumber())) {
//            throw new InputException("标的信息有误");
//        }
//
//        LoanMoney loanMoney = LoanMoney.newInstance(loan);
//
//        Decimal repayInterestD = loanMoney.shouldRepayInterestD();
//
//        Repay repay = new Repay();
//        repay.setRepayId(ToolGen.genId(GenConstant.REDIS_KEY_REPAY_ID))
//                .setLoanId(loan.getLoanId())
//                .setLoanNumber(loan.getLoanNumber())
//                .setInterestD(repayInterestD.moneyValue())
//                .setShouldRepayMoneyD(repayInterestD.add(loan.getLoanAmountD()).moneyValue())
//                .setOverD(0D)
//                .setRepayStatus(0)//代表未开始还款
//                .setCompensateMoneyD(Decimal.instance(loan.getLoanAmountD()).mul(loanInfo.getCompensateD()).div(100).moneyValue())
//
//                .setLoanUserId(loan.getUserId())
//                .setLoanUserName(loan.getUserName())
//                .setLoanUserPayPlatformID(loan.getUserPayPlatformID())
//        ;
//
//        try {
//            repay = repayDao.insertOne(repay);
//            return repay != null;
//        } catch (DaoException e) {
//            log.warn(ToolFormat.toException(e), e);
//            return false;
//        }
//    }
//
//    @Override
//    public Boolean putRepayUser(Loan loan, PurchaseLoanRecord purchaseLoanRecord) {
//
//        Repay repay = new Repay().setLoanId(loan.getLoanId());
//
//        repay = repayDao.findOne(repay);
//
//        LoanMoney loanMoney = LoanMoney.newInstance(loan);
//
//        RepayUser repayUser = new RepayUser();
//        repayUser.setRepayUserId(ToolGen.genId(GenConstant.REDIS_KEY_REPAYUSER_ID))
//                .setRepayId(repay.getRepayId())
//
//                .setLoanId(purchaseLoanRecord.getLoanId())
//                .setLoanNumber(purchaseLoanRecord.getLoanNumber())
//
//                .setUserId(purchaseLoanRecord.getUserId())
//                .setUserName(purchaseLoanRecord.getUserName())
//                .setUserPayPlatformID(purchaseLoanRecord.getPayPlatformID())
//
//                .setBuyMoneyD(purchaseLoanRecord.getAmount())
//                .setBuyDate(purchaseLoanRecord.getDate())
//                .setBuyOrderNo(purchaseLoanRecord.getOrderNo())
//
//                .setShouldRepayMoneyD(loanMoney.shouldRepayInterestD(purchaseLoanRecord.getAmount()).add(purchaseLoanRecord.getAmount()).moneyValue())
//                .setRepayStatus(0)//代表未开始还款
//
//                .setLoanUserId(loan.getUserId())
//                .setLoanUserName(loan.getUserName())
//                .setLoanUserPayPlatformId(loan.getUserPayPlatformID())
//        ;
//
//        try {
//            repayUser = repayUserDao.insertOne(repayUser);
//            return repayUser != null;
//        } catch (DaoException e) {
//            log.warn(ToolFormat.toException(e), e);
//            return false;
//        }
//    }
//
//    /**
//     * 一般在满标放款之后触发
//     *
//     * @param loan:
//     */
//    @Override
//    public void beginRepay(Loan loan) throws InputException {
//        Long loanId = loan.getLoanId();
//
//        Repay searchRepay = new Repay();
//        searchRepay.setLoanId(loanId);
//
//        RepayUser searchRepayUser = new RepayUser();
//        searchRepayUser.setLoanId(loanId);
//
//        Paging<RepayUser> repayUserPaging = repayUserDao.findPage(searchRepayUser, PageInfo.getMax(), null);
//
//        if ((searchRepay = repayDao.findOne(searchRepay)) == null || repayUserPaging.getTotalCount() < 1) {
//            throw new InputException("标的信息有误");
//        }
//
//        LoanMoney loanMoney = LoanMoney.newInstance(loan);
//
//        Date now = ToolDate.getDate();
//        Date endDate = loanMoney.shouldRepayDate(now);
//
//        repayUserPaging.getList().forEach(one -> {
//            one.setRepayStatus(1)
//                    .setShouldRepayDate(endDate)
//            ;
//            repayUserDao.updateOne(one);
//        });
//
//        searchRepay.setRepayStatus(1)
//                .setShouldRepayDate(endDate)
//                .setBeginRepayDate(now)
//        ;
//
//        //fixme
//        repayDao.updateOne(searchRepay);
//
//        loan.setEndDate(endDate);
//        //fixme
//        LoanDao loanDao = Duang.duang(LoanDao.class);
//        loanDao.updateOne(loan);
//    }
//
//    @Override
//    public LoanDetailVO checkExecRequestRepay(Long loanId) throws RepayException {
//        Map<String, Object> params = Maps.newHashMap();
//        params.put("loanId", loanId);
//        JsonResult<LoanDetailVO> jsonResult = super.send("checkExecRequestRepay", params, TypeConst.JR.LoanDetailVOType);
//
//        if (jsonResult.getHaveError()) {
//            throw new RepayException(jsonResult.getErrMsg());
//        }
//        //说明校验可以还款
//        LoanDetailVO loanDetailVO = jsonResult.getData();
//
//        //校验用户信息
//        Long userId = jsonResult.getData().getLoan().getUserId();
//        UserModel userModel = userService.findOneById(userId);
//
//        if (userModel == null) {
//            throw new RepayException("借款人信息为空");
//        }
//        Repay repay = loanDetailVO.getRepay();
//        Decimal loanUserBalance = Decimal.instance(userModel.getAccountModel().getBalance());
//        Decimal realRepayMoneyD = Decimal.instance(repay.getRealRepayMoneyD());
//        if (loanUserBalance.moneyValue() < realRepayMoneyD.moneyValue()) {
//            throw new RepayException("还款人账户余额" + loanUserBalance.doubleValue() + "元,不足还款额" + realRepayMoneyD.moneyValue() + "元");
//        }
//        loanDetailVO.setLoanUser(userModel);
//        return loanDetailVO;
//    }
//
//    /**
//     * 正常还款请求
//     *
//     * @param loanId：标的id
//     */
//    @Override
//    public boolean execRequestRepay(Long loanId) throws RepayException {
//        if (loanId == null) {
//            throw new RepayException("请传入标的主键");
//        }
//        ILock lock = ToolLock.Loan.loanIdLock(loanId);
//        if (lock != null) {
//            try {
//                LoanDetailVO loanDetailVO = checkExecRequestRepay(loanId);
//                Loan loan = loanDetailVO.getLoan();
////                //3.进行调用第三方还款操作
////
//                String repayOrderNo = ToolOrderCode.getOrderCode(loan.getLoanId(), ToolOrderCode.REPAY_ORDER_CODE);//生成还款订单号
//                //成功后修改我方数据
//                Map<String, Object> params = Maps.newHashMap();
//                params.put("repayOrderNo", repayOrderNo);
//                params.put("loanId", loan.getLoanId());
//
//                //修改本地状态
//                JsonResult<Boolean> jsonResult = super.send("execRequestRepaySuccess", params, TypeConst.JR.BooleanType);
//                if (jsonResult.getHaveError()) {
//                    throw new RepayException(jsonResult.getErrMsg());
//                }
//
//                //请求第三方接口
//                Map result = thirdPartyService.payPlatformTransferRepay(
//                        loanDetailVO.getLoanUser().getAccountModel().getPayPlatformID(), repayOrderNo,
//                        loan, PayerMap.getReceiveUrl("adminRepay"));//获取请求第三方接口参数
//                //请求第三方接口
//                HttpReceive httpReceive = ToolHttp.sendPost(result.get("submitUrl").toString(), result);
//                // responseBody = URLDecoder.decode(responseBody, "UTF-8");
//                if (httpReceive.getHaveError()) {
//                    jsonResult = super.send("execRequestRepayError", params, TypeConst.JR.BooleanType);
//                    if (jsonResult.getHaveError() || !jsonResult.getData()) {
//                        throw new RepayException("请求还款接口失败,还原数据失败");
//                    }
//                    throw new RepayException("请求还款接口失败,还原数据成功");
//                }
//                String responseBody = httpReceive.getResponseBody();
//                TransferReturn transferReturn = treansferJson(responseBody);
//                String resultCode = transferReturn.getResultCode();
//                //TODO   等待修改--cl
//                if ("88".equals(resultCode) || "87".equals(resultCode)) {
//                    return Boolean.TRUE;
//                }
//
//                //若第三方失败则将上面逻辑修改回
//                jsonResult = super.send("execRequestRepayError", params, TypeConst.JR.BooleanType);
//                if (jsonResult.getHaveError() || !jsonResult.getData()) {
//                    throw new RepayException(jsonResult.getErrMsg());
//                }
//                return jsonResult.getData();
//            } catch (Exception e) {
//                throw new RepayException(e);
//            } finally {
//                lock.unlock();//解锁
//            }
//        } else {
//            throw new RepayException("当前标的正在占用中,请稍后再试.");
//        }
//
//    }
//
//    private TransferReturn treansferJson(String json) {
//        json = json.trim();
//        System.out.println(json);
//        char c = json.charAt(0);
//        if (c == '{') {
//            TransferReturn transferReturn = ToolJson.jsonToModel(json, TransferReturn.class);
//            return transferReturn;
//        } else if (c == '[') {
//            List<TransferReturn> transferReturnList = ToolJson.jsonToModelList(json, TransferReturn.class);
//            return transferReturnList.get(0);
//        }
//        return null;
//    }
//
//    /**
//     * 提前还款请求 目前提前还款与正常还款一致
//     *
//     * @param loanId：
//     */
//    @Override
//    public boolean execRequestAdvanceRepay(Long loanId) throws RepayException {
//        return execRequestRepay(loanId);
//    }
//
//    /**
//     * 还款统一入口
//     *
//     * @param loanId：标的id
//     * @param payerKey：还款请求第三方参数获取
//     * @param status：还款状态，0表示提前还款，1表示正常还款，2表示逾期还款
//     *
//     * @return
//     *
//     * @throws RepayException
//     */
//    @Override
//    public Map<String, Object> execRepay(Long loanId, String payerKey, int status) throws RepayException {
//        Map<String, Object> myResult = Maps.newHashMap();
//        if (loanId == null) {
//            throw new RepayException("请传入标的主键");
//        }
//        ILock lock = ToolLock.Loan.loanIdLock(loanId);
//        if (lock != null) {
//            try {
//                LoanDetailVO loanDetailVO = checkExecRequestRepay(loanId);
//                Loan loan = loanDetailVO.getLoan();
////                //3.进行调用第三方还款操作
////
//                String repayOrderNo = ToolOrderCode.getOrderCode(loan.getLoanId(), ToolOrderCode.REPAY_ORDER_CODE);//生成还款订单号
//                //成功后修改我方数据
//                Map<String, Object> params = Maps.newHashMap();
//                params.put("repayOrderNo", repayOrderNo);
//                params.put("loanId", loan.getLoanId());
//
//                //修改本地状态
//                JsonResult<Boolean> jsonResult = super.send("execRequestRepaySuccess", params, TypeConst.JR.BooleanType);
//                if (jsonResult.getHaveError()) {
//                    throw new RepayException(jsonResult.getErrMsg());
//                }
//
//                //请求第三方接口
//                Map result = thirdPartyService.payPlatformTransferRepay(
//                        loanDetailVO.getLoanUser().getAccountModel().getPayPlatformID(), repayOrderNo,
//                        loan, PayerMap.getReceiveUrl(payerKey));//获取请求第三方接口参数
//                //请求第三方接口
//                HttpReceive httpReceive = ToolHttp.sendPost(result.get("submitUrl").toString(), result);
//                log.info("-cl-还款调用第三方接口同步返回数据:"+httpReceive.getResponseBody());
//                // responseBody = URLDecoder.decode(responseBody, "UTF-8");
//                if (httpReceive.getHaveError()) {
//                    jsonResult = super.send("execRequestRepayError", params, TypeConst.JR.BooleanType);
//                    if (jsonResult.getHaveError() || !jsonResult.getData()) {
//                        throw new RepayException("请求还款接口失败,还原数据失败");
//                    }
//                    throw new RepayException("请求还款接口失败,还原数据成功");
//                }
//                String responseBody = httpReceive.getResponseBody();
//                TransferReturn transferReturn = treansferJson(responseBody);
//                String resultCode = transferReturn.getResultCode();
//                myResult.put("transferReturn", transferReturn);
//                if ("88".equals(resultCode) || "87".equals(resultCode)) {
//                    myResult.put("result", Boolean.TRUE);
//                    myResult.put("loan", loan);
//                    myResult.put("repay", loanDetailVO.getRepay());
//                    return myResult;
//                }
//
//                //若第三方失败则将上面逻辑修改回
//                jsonResult = super.send("execRequestRepayError", params, TypeConst.JR.BooleanType);
//                if (jsonResult.getHaveError() || !jsonResult.getData()) {
//                    throw new RepayException(jsonResult.getErrMsg());
//                }
//                myResult.put("result", Boolean.FALSE);
//                return myResult;
//            } catch (Exception e) {
//                throw new RepayException(e);
//            } finally {
//                lock.unlock();//解锁
//            }
//        } else {
//            throw new RepayException("当前标的正在占用中,请稍后再试.");
//        }
//    }
//
//    /**
//     * 正常到期还款成功时请求回调处理
//     *
//     * @param received：第三方参数
//     */
//    @Override
//    public boolean execRepaySuccessAfter(Map<String, Object> received) throws RepayException,PayerErrorException {
//
//        //处理第三方返回的数据
//
//        TransferReturn transferReturn = thirdPartyService.payPlatformTransferReturn(received);
//        if (transferReturn == null) {
//            log.info(SysConfigConstant.MY_LOG_NID+"还款操作异步回调service:校验参数失败");
//            throw new PayerErrorException("校验第三方返回数据失败");
//        }
//
//        String loanJsonList = transferReturn.getLoanJsonList();
//        try {
//            loanJsonList = URLDecoder.decode(loanJsonList, "UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//            log.info(SysConfigConstant.MY_LOG_NID+"还款操作异步回调service:解码失败");
//            throw new PayerErrorException("还款第三方回调返回数据有误，解码失败");
//        }
//        List<TransferReturnJsonList> transferReturnJsonLists = ToolJson.jsonToModelList(loanJsonList, TransferReturnJsonList.class);
//        if (ToolStr.isBlank(transferReturn.getRemark2())) {
//            log.info(SysConfigConstant.MY_LOG_NID+"还款操作异步回调service:remark2不能为空");
//            throw new PayerErrorException("还款第三方回调返回数据有误，remark2不能为空");
//        }
//        //处理第三方返回的数据
//
//        //第三方处理失败时本地处理
//        Long loanId = Long.parseLong(transferReturn.getRemark2());
//        if (!"88".equals(transferReturn.getResultCode()) && !"87".equals(transferReturn.getResultCode())) {//第三方处理失败
//            Map<String, Object> params = Maps.newHashMap();
//            params.put("loanId", loanId);
//            ILock lock = ToolLock.Loan.loanIdLock(loanId);
//            if (lock != null) {
//                try {
//                    JsonResult<Boolean> jsonResult = super.send("execRequestRepayError", params, TypeConst.JR.BooleanType);
//                    if (jsonResult.getHaveError() || !jsonResult.getData()) {
//                        log.info(SysConfigConstant.MY_LOG_NID+"还款操作异步回调service:还款失败,还原数据失败");
//                        throw new PayerErrorException("还款失败,还原数据失败");
//                    } else {
//                        return true;
//                    }
//                } catch (Exception e) {
//                    throw new PayerErrorException(e.getMessage());
//                } finally {
//                    lock.unlock();
//                }
//            } else {
//                log.info(SysConfigConstant.MY_LOG_NID+"还款操作异步回调service:当前标的正在占用，第三方会自动重试");
//                throw new PayerErrorException("当前标的正在占用，第三方会自动重试");
//            }
//        }
//        //第三方处理失败时本地处理
//
//        //第三方返回成功时本地处理
//        ILock lock = ToolLock.Loan.loanIdLock(loanId);
//        if (lock != null) {
//            WorkflowWrapper workflow = WorkflowWrapper.build("loan:repay:loanId:" + loanId, 1);
//            try {
//                //校验还款是否可操作
//                Map<String, Object> loanParams = Maps.newHashMap();
//                loanParams.put("loanId", loanId);
//                JsonResult<LoanDetailVO> checkResult = super.send("checkExecRepayAfter", loanParams, TypeConst.JR.LoanDetailVOType);
//                if (checkResult.getHaveError()) {
//                    log.info(SysConfigConstant.MY_LOG_NID+"还款操作异步回调service:"+checkResult.getErrMsg());
//                    throw new PayerErrorException(checkResult.getErrMsg());
//                }
//                //校验还款是否可操作
//
//                //校验还款是否已处理
//                Loan loan = checkResult.getData().getLoan();
//                Repay repay = checkResult.getData().getRepay();
//                if (loan.getLoanStatus() != 3 || repay.getRepayStatus() != 5) {//表示还款完成
//                    log.info(SysConfigConstant.MY_LOG_NID+"还款操作异步回调service:还款已处理,标的状态:"
//                            + LoanStatus.get(loan.getLoanStatus()) +
//                            ",还款状态:" + RepayStatus.get(repay.getRepayStatus()));
//                    return true;
//                }
//                //校验还款是否已处理
//
//                //获取借款人信息并校验借款人
//                UserModel loanUser = userService.findOneById(repay.getLoanUserId());
//                Decimal loanUserBalance = Decimal.instance(loanUser.getAccountModel().getBalance());
//                Decimal realRepayMoneyD = Decimal.instance(repay.getRealRepayMoneyD());
//                workflow.begin("loanUser.valid", new Param("loanUser", loanUser));
//                if (loanUserBalance.moneyValue() < realRepayMoneyD.moneyValue()) {
//                    log.info(SysConfigConstant.MY_LOG_NID+"还款操作异步回调service:借款余额不足,"
//                            +"您账户余额" + loanUserBalance.doubleValue() + "元,不足还款额"
//                            + realRepayMoneyD.moneyValue() + "元");
//                    throw new InputException("您账户余额" + loanUserBalance.doubleValue() + "元,不足还款额" + realRepayMoneyD.moneyValue() + "元");
//                }
//
//                //获取借款人信息并校验借款人
//
//
//                workflow.finish(true);
//                //1.请求loan，修改标的
//                workflow.begin("repayService.execRepayAfter", new Param("repay", repay), new Param("loan", loan));
//
//                //标的微服务处理
//                JsonResult<Boolean> loanDbResult = super.send("execRepaySuccessAfter", loanParams, TypeConst.JR.BooleanType);
//                if (loanDbResult.getHaveError()) {
//                    log.info(SysConfigConstant.MY_LOG_NID+"还款操作异步回调service:修改标的相关信息有误"+loanDbResult.getErrMsg());
//                    throw new RepayException(loanDbResult.getErrMsg());
//                }
//                //标的微服务处理
//
//                workflow.finish(true);
//
//                //预处理数据
//                List<RepayUser> repayUsers = checkResult.getData().getRepayUserPaging().getList();
//                workflow.begin("loanUser.valid", new Param("loanUser", loanUser), new Param("repayUserList", repayUsers));
//
//                //封装需要修改用户的资金信息
//                List<UserAccountVo> list = Lists.newArrayList();
//
//                list.add(new UserAccountVo().setUserId(repay.getLoanUserId()).setMoney(-repay.getRealRepayMoneyD()));
//
//                //还款流水
//                List<AmountFlow> repayAmountFlowList = Lists.newArrayList();
//                DatePlus now = new DatePlus(ToolDate.getDate());
//                //收款流水
//                List<AmountFlow> getRepayAmountFlowList = Lists.newArrayList();
//                repayUsers.forEach(repayUser -> {
//                    LoanMoney loanMoney = LoanMoney.newInstance(loan);
//                    Double collectD = loanMoney.shouldRepayInterestD(repayUser.getBuyMoneyD()).moneyValue();//计算出本次交易的待收收益
//                    list.add(new UserAccountVo().setUserId(repayUser.getUserId())
//                            .setMoney(repayUser.getRealRepayMoneyD())
//                            .setCollect(-collectD)//减去预收益
//                            .setProfit(Decimal.instance(repayUser.getRealRepayMoneyD())
//                                    .sub(repayUser.getBuyMoneyD()).moneyValue()));//添加累计收益(实际)
//                    //2 添加还款流水
//                    AmountFlow repayAmountFlow = AmountFlowBuild.build(
//                            0//表示成功了
//                            , now.toDate()//设置当前时间
//                            , repayUser.getRealRepayMoneyD()//交易金额
//                            , repay.getRepayOrderNo()//流水号
//                            , repayUser.getUserId()//in
//                            , repayUser.getUserName()//in
//                            , repayUser.getLoanUserId()//out
//                            , repayUser.getLoanUserName()//out
//                            , 2//类型表示还款
//                            , loan
//                    );
//                    repayAmountFlowList.add(repayAmountFlow);
//
//                    //3 添加收款流水
//                    AmountFlow getRepayAmountFlow = AmountFlowBuild.build(
//                            0//表示成功了
//                            , now.toDate()//设置当前时间
//                            , repayUser.getRealRepayMoneyD()//交易金额
//                            , repay.getRepayOrderNo()//流水号
//                            , repayUser.getLoanUserId()//in
//                            , repayUser.getLoanUserName()//in
//                            , repayUser.getUserId()//out
//                            , repayUser.getUserName()//out
//                            , 5//类型表示还款
//                            , loan
//                            , "作为投资者收款"
//                    );
//                    getRepayAmountFlowList.add(getRepayAmountFlow);
//                });
//                //预处理数据
//
//                //执行修改借款人金额
//                boolean updateUserMoneyResult = userService.execRepayAfter(list);
//                if (!updateUserMoneyResult) {
//                    log.info(SysConfigConstant.MY_LOG_NID+"还款操作异步回调service:修改用户余额失败");
//                    throw new RepayException("修改用户余额失败");
//                }
//                //执行修改借款人金额
//
//                workflow.finish(true);
//                //执行插入流水
//                List<AmountFlow> amountFlowList = Lists.newArrayList();
//                amountFlowList.addAll(repayAmountFlowList);
//                amountFlowList.addAll(getRepayAmountFlowList);
//                workflow.begin("amountFlow.execRepayAfter", new Param("amountFlowList", amountFlowList));
//                boolean insertAmountFlowResult = capitalService.insertCapitals(amountFlowList);
//                if(!insertAmountFlowResult){
//                    log.info(SysConfigConstant.MY_LOG_NID+"还款操作异步回调service:插入流水失败");
//                    throw new RepayException("插入流水失败");
//                }
//                //执行插入流水
//                workflow.finish(true);
//                return true;
//            }catch (PayerErrorException e){
//                throw new PayerErrorException(e.getMessage());
//            } catch (Exception e) {
//                workflow.error(e);
//                throw new RepayException(e);
//            } finally {
//                lock.unlock();
//            }
//        } else {
//            log.info(SysConfigConstant.MY_LOG_NID+"还款操作异步回调service:当前标的正在占用，第三方会自动重试");
//            throw new PayerErrorException("当前标的正在占用，第三方会自动重试");
//        }
//
//        //第三方返回成功时本地处理
//    }
//
//
//    /**
//     * 正常到期还款
//     *
//     * @param loanId：
//     *         主键
//     */
//    @Override
//    public void execRepay(Long loanId) throws RepayException {
//        //因为算钱方面的业务都放到微服务的计时任务中了,所以还款扣款步骤都一样
//        execAdvanceRepay(loanId);
//    }
//
//    /**
//     * 提前还款
//     *
//     * @param loanId
//     *         主键
//     *
//     * @throws InputException
//     */
//    @Override
//    public void execAdvanceRepay(Long loanId) throws RepayException {
//
//        if (loanId == null) {
//            throw new RepayException("请传入标的主键");
//        }
//
//        ILock lock = ToolLock.Loan.loanIdLock(loanId);
//        if (lock != null) {
//            WorkflowWrapper workflow = WorkflowWrapper.build("loan:repay:loanId:" + loanId, 1);
//            try {
//                LoanDetailVO loanDetailVO = loanWrapper.findOneByLoanId(loanId, null, false);
//
//                if (loanDetailVO == null || loanDetailVO.getLoan() == null || loanDetailVO.getLoanInfo() == null) {
//                    throw new InputException("标的未找到");
//                }
//
//                Integer loanStatus = loanDetailVO.getLoan().getLoanStatus();
//                if (loanStatus != 3) {
//                    throw new InputException("该标" + LoanStatus.get(loanStatus));
//                }
//
//                Repay repay = loanDetailVO.getRepay();
//
//                if (repay == null) {
//                    throw new InputException("还款记录未找到");
//                }
//
//                DatePlus now = new DatePlus(ToolDate.getDate());
//
//                Paging<RepayUser> repayUsers = loanDetailVO.getRepayUserPaging();
//
//                if (repayUsers == null || repayUsers.getList() == null || repayUsers.getList().size() < 1) {
//                    throw new InputException("还款明细未找到");
//                }
//
//                UserService userService = Duang.duang(UserServiceImpl.class);
//
//                UserModel loanUser = loanDetailVO.getLoanUser();
//                Decimal loanUserBalance = Decimal.instance(loanUser.getAccountModel().getBalance());
//                Decimal realRepayMoneyD = Decimal.instance(repay.getRealRepayMoneyD());
//                workflow.begin("loanUser.valid", new Param("loanUser", loanUser));
//                if (loanUserBalance.moneyValue() < realRepayMoneyD.moneyValue()) {
//                    throw new InputException("您账户余额" + loanUserBalance.doubleValue() + "元,不足还款额" + realRepayMoneyD.moneyValue() + "元");
//                }
//                workflow.finish(true);
//
//                workflow.begin("repayUsers.getList().forEach");
//                //1 更新还款明细实体 ok
//                repayUsers.getList().forEach(repayUser -> {
//                    workflow.beginSub(new Param("repayUserId", repayUser.getRepayId()));
//
//                    String orderNo = "orderNo:" + ToolRandoms.getRandomStr();
//
//                    repayUser.setRealRepayDate(now.toDate())
//                            .setRepayStatus(4)
//                            .setRepayOrderNo(orderNo)
//                    ;
//                    repayUserDao.updateOne(repayUser);
//
//                    //2 添加还款流水
//                    AmountFlow repayAmountFlow = AmountFlowBuild.build(
//                            0//表示成功了
//                            , now.toDate()//设置当前时间
//                            , repayUser.getRealRepayMoneyD()//交易金额
//                            , orderNo//流水号
//                            , repayUser.getUserId()//in
//                            , repayUser.getUserName()//in
//                            , repayUser.getLoanUserId()//out
//                            , repayUser.getLoanUserName()//out
//                            , 2//类型表示还款
//                            , loanDetailVO.getLoan()
//                    );
//
//                    capitalService.insertOne(repayAmountFlow);//保存流水
//
//                    //3 添加收款流水
//                    AmountFlow getRepayAmountFlow = AmountFlowBuild.build(
//                            0//表示成功了
//                            , now.toDate()//设置当前时间
//                            , repayUser.getRealRepayMoneyD()//交易金额
//                            , orderNo//流水号
//                            , repayUser.getLoanUserId()//in
//                            , repayUser.getLoanUserName()//in
//                            , repayUser.getUserId()//out
//                            , repayUser.getUserName()//out
//                            , 5//类型表示还款
//                            , loanDetailVO.getLoan()
//                            , "作为投资者收款"
//                    );
//
//                    capitalService.insertOne(getRepayAmountFlow);//保存流水
//
//                    Long buyUserId = repayUser.getUserId();
//                    UserModel buyUser = userService.findOneById(buyUserId);
//                    Decimal balance = Decimal.instance(buyUser.getAccountModel().getBalanceD());
//                    AccountModel buyUserAccountModel = buyUser.getAccountModel();
//                    //添加余额
//                    buyUserAccountModel.setBalance(balance.add(repayUser.getRealRepayMoneyD()).moneyValue());
//                    //减去预收益
//                    buyUserAccountModel.setCollect(Decimal.instance(buyUserAccountModel.getCollectD()).sub(repayUser.getShouldRepayMoneyD()).moneyValue());
//                    //添加累计收益(实际)
//                    buyUserAccountModel.setProfit(
//                            Decimal.instance(repayUser.getRealRepayMoneyD()).sub(repayUser.getBuyMoneyD())
//                                    .add(buyUserAccountModel.getProfitD())
//                                    .moneyValue()
//                    );
//                    buyUser.setAccountModel(buyUserAccountModel);
//                    userService.updateOne(buyUser);
//                });
//                workflow.finish(true);
//
//                //4 更新还款实体 ok
//                repay.setRealRepayDate(now.toDate())
//                        .setRepayStatus(4)
//                ;
//                workflow.begin("repayDao.updateOne", new Param("repay", repay));
//                Boolean updateRepayFlag = repayDao.updateOne(repay);
//                if (!updateRepayFlag) {
//                    throw new RepayException("修改还款记录失败");
//                }
//                workflow.finish(true);
//
//                workflow.begin("loanWrapper.changeLoanStatus", new Param("loanId", loanId));
//                //5 改变标的状态 ok
//                Boolean changeLoanStatusFlag = loanWrapper.changeLoanStatus(loanId, null, 5);
//                if (!changeLoanStatusFlag) {
//                    throw new RepayException("修改标的状态失败");
//                }
//                workflow.finish(true);
//
//                //6 改变用户信息 ok
//                Decimal balance = Decimal.instance(loanUser.getAccountModel().getBalanceD());
//                loanUser.getAccountModel().setBalance(balance.sub(realRepayMoneyD).moneyValue());
//                workflow.begin("userService.updateOne", new Param("loanUser", loanUser));
//                boolean updateLoanUserFlag = userService.updateOne(loanUser);
//                if (!updateLoanUserFlag) {
//                    throw new RepayException("修改借款用户信息失败");
//                }
//                workflow.finish(true);
//
//            } catch (Exception e) {
//                workflow.error(e);
//                throw new RepayException(e);
//            } finally {
//                lock.unlock();
//            }
//        } else {
//            throw new RepayException("当前标的正在占用中,请稍后再试.");
//        }
//    }
//
//    @Override
//    public Repay findRepayByPK(Long loanId, String loanNumber) throws InputException {
//        Boolean idIsNull = true;
//        Repay searchRepay = new Repay();
//        if (loanId != null) {
//            searchRepay.setLoanId(loanId);
//            idIsNull = false;
//        }
//        if (ToolStr.notBlank(loanNumber)) {
//            searchRepay.setLoanNumber(loanNumber);
//            idIsNull = false;
//        }
//
//        if (idIsNull) {
//            throw new InputException("请传入标的主键,loanId或者loanNumber");
//        }
//
//        try {
//            searchRepay = repayDao.findOne(searchRepay);
//
//            if (searchRepay == null) {
//                throw new DaoException(DbType.FindOne);
//            }
//
//            return searchRepay;
//        } catch (DaoException e) {
//            log.warn(ToolFormat.toException(e), e);
//            return null;
//        }
//    }
//
//    //region facefeel新增
//
//    @Override
//    public Paging<Repay> findPagingRepayByUserId(Long userId) {
//
//        Paging<Repay> page;
//        if (userId == null) {
//            throw new InputException("请传入用户主键");
//        }
//
//        try {
//            page = repayUserDao.findPage(new Repay().setLoanUserId(userId), PageInfo.getMax(), null);
//
//            if (page == null) {
//                throw new DaoException(DbType.FindPage);
//            }
//
//            return page;
//        } catch (DaoException e) {
//            log.warn(ToolFormat.toException(e), e);
//            return null;
//        }
//    }
//
//    @Override
//    public Paging<RepayUser> findPagingRepayUsersByUserId(Long userId) throws InputException {
//
//        Paging<RepayUser> page;
//        if (userId == null) {
//            throw new InputException("请传入用户主键");
//        }
//
//        try {
//            page = repayUserDao.findPage(new RepayUser().setUserId(userId), PageInfo.getMax(), null);
//
//            if (page == null) {
//                throw new DaoException(DbType.FindPage);
//            }
//
//            return page;
//        } catch (DaoException e) {
//            log.warn(ToolFormat.toException(e), e);
//            return null;
//        }
//    }
//
//    //endregion
//
//    @Override
//    public Paging<RepayUser> findPagingRepayUsersByLoanId(Long loanId, PageInfo pageInfo) {
//        try {
//            return repayUserDao.findPage(new RepayUser().setLoanId(loanId), pageInfo, new BoolParams());
//        } catch (DaoException e) {
//            log.warn(ToolFormat.toException(e), e);
//            return null;
//        }
//    }
//}
